<template>
  <div class="search-results">
    <div class="search-header">
      <h2>搜索结果: {{ searchQuery }}</h2>
      <el-divider></el-divider>
    </div>
    
    <div v-if="loading" class="loading">
      <el-skeleton :rows="6" animated />
    </div>
    
    <div v-else-if="noResults" class="empty-result">
      <el-empty description="暂无搜索结果">
        <div slot="description">
          <p>未找到与"{{ searchQuery }}"相关的商品或商家</p>
          <small v-if="searchErrors">可能出现了问题: {{ searchErrors }}</small>
        </div>
      </el-empty>
    </div>
    
    <div v-else>
      <!-- 商家搜索结果 -->
      <div v-if="merchants.length > 0" class="merchant-results">
        <h3 class="section-title">商家 ({{ merchants.length }})</h3>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="merchant in merchants" :key="merchant.id">
            <el-card class="merchant-card" shadow="hover" @click.native="goToShop(merchant.id)">
              <div class="merchant-img">
                <el-image :src="merchant.shopLogo || 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'" fit="cover">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
              <div class="merchant-content">
                <div class="merchant-name">{{ merchant.shopName }}</div>
                <div class="merchant-rating">
                  <el-rate v-model="merchant.rating" disabled text-color="#ff9900"></el-rate>
                  <span>{{ merchant.rating }}</span>
                </div>
                <div class="merchant-info">
                  <span>起送价 ¥{{ merchant.minPrice || 0 }}</span>
                  <span>配送费 ¥{{ merchant.deliveryFee || 0 }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-divider v-if="products.length > 0"></el-divider>
      </div>
      
      <!-- 商品搜索结果 -->
      <div v-if="products.length > 0" class="product-results">
        <h3 class="section-title">商品 ({{ products.length }})</h3>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="product in products" :key="product.id">
            <el-card class="product-card" shadow="hover" @click.native="viewProduct(product.id)">
              <div class="product-img">
                <el-image :src="product.image || `https://picsum.photos/300/300?random=${product.id}`" fit="cover">
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
              <div class="product-content">
                <div class="product-name">{{ product.name }}</div>
                <div class="product-price">¥{{ (product.price && product.price.toFixed(2)) || '0.00' }}</div>
                <div class="product-merchant">{{ product.merchantName || '查看详情' }}</div>
                <div class="product-sales">月销 {{ product.sales || 0 }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      
      <div class="pagination-container">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="totalItems">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import { searchProducts } from '@/api/product'

export default {
  name: 'SearchResults',
  data() {
    return {
      searchQuery: '',
      products: [],
      merchants: [],
      loading: true,
      currentPage: 1,
      pageSize: 12,
      productTotal: 0,
      merchantTotal: 0,
      searchErrors: null
    }
  },
  computed: {
    totalItems() {
      return this.productTotal + this.merchantTotal;
    },
    noResults() {
      return this.products.length === 0 && this.merchants.length === 0;
    }
  },
  created() {
    // 获取URL查询参数
    const queryParam = this.$route.query.q;
    const keywordParam = this.$route.query.keyword;
    console.log('Query parameters received:', { q: queryParam, keyword: keywordParam });
    
    this.searchQuery = this.$route.query.q || this.$route.query.keyword || '';
    this.fetchResults();
  },
  watch: {
    // 监听路由变化，当搜索内容变化时重新搜索
    '$route.query': function(newQuery) {
      this.searchQuery = newQuery.q || newQuery.keyword || ''
      this.currentPage = 1
      this.fetchResults()
    }
  },
  methods: {
    fetchResults() {
      if (!this.searchQuery) {
        this.products = []
        this.merchants = []
        this.loading = false
        return
      }
      
      this.loading = true
      console.log('Searching with query:', this.searchQuery) // Debug log
      
      // Prepare search parameters
      const params = {
        keyword: this.searchQuery,
        page: this.currentPage,
        size: this.pageSize
      }
      console.log('Search params:', params) // Debug log
      
      searchProducts(params)
        .then(res => {
          console.log('Search API response:', res) // Debug log
          
          // Handle the response data
          if (res && res.code === 200) {
            const data = res.data || {};
            
            // 处理商品数据
            if (data.products) {
              this.products = data.products.records || [];
              this.productTotal = data.products.total || 0;
            } else {
              this.products = [];
              this.productTotal = 0;
            }
            
            // 处理商家数据
            if (data.merchants) {
              this.merchants = data.merchants.records || [];
              this.merchantTotal = data.merchants.total || 0;
            } else {
              this.merchants = [];
              this.merchantTotal = 0;
            }
          } else {
            this.$message.error(res && res.message || '搜索失败');
            this.products = [];
            this.merchants = [];
            this.searchErrors = res && res.message || '搜索失败';
          }
        })
        .catch(error => {
          console.error('搜索失败:', error)
          this.$message.error('搜索失败')
          this.products = []
          this.merchants = []
          this.searchErrors = error.message || '搜索失败';
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchResults()
    },
    viewProduct(productId) {
      this.$router.push(`/product/${productId}`)
    },
    goToShop(shopId) {
      this.$router.push(`/shop/${shopId}`)
    }
  }
}
</script>

<style scoped>
.search-results {
  padding: 20px;
}

.search-header {
  margin-bottom: 20px;
}

.search-header h2 {
  font-size: 18px;
  color: #303133;
}

.section-title {
  font-size: 16px;
  margin: 10px 0 20px;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #f56c6c;
  border-radius: 2px;
}

.loading {
  padding: 20px;
}

.empty-result {
  padding: 50px 0;
}

.merchant-results, .product-results {
  margin-bottom: 30px;
}

.merchant-card, .product-card {
  cursor: pointer;
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
}

.merchant-card:hover, .product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.merchant-img, .product-img {
  height: 150px;
  overflow: hidden;
}

.merchant-content, .product-content {
  padding: 10px 0;
}

.merchant-name, .product-name {
  font-size: 14px;
  margin-bottom: 8px;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  font-weight: bold;
}

.merchant-rating {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.merchant-rating .el-rate {
  display: inline-block;
  margin-right: 5px;
}

.merchant-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #606266;
}

.product-price {
  font-size: 18px;
  color: #f56c6c;
  margin-bottom: 5px;
}

.product-merchant {
  font-size: 12px;
  color: #606266;
  margin-bottom: 5px;
}

.product-sales {
  font-size: 12px;
  color: #909399;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}
</style> 